<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    title="还款计划"
    width="900px"
    @opened="loadRepaymentPlans"
  >
    <div class="repayment-plan-content">
      <div class="plan-header" v-if="loanInfo">
        <h4>贷款信息</h4>
        <div class="loan-info">
          <span>贷款编号：#{{ loanInfo.id }}</span>
          <span>贷款金额：¥{{ formatAmount(loanInfo.amount) }}</span>
          <span>还款方式：{{ getRepaymentMethodText(loanInfo.repaymentMethod) }}</span>
        </div>
      </div>

      <div class="plans-table" v-loading="loading">
        <el-table :data="repaymentPlans" stripe>
          <el-table-column prop="periodNumber" label="期数" width="80" align="center">
            <template #default="{ row }">
              第{{ row.periodNumber }}期
            </template>
          </el-table-column>
          <el-table-column prop="repaymentDate" label="应还日期" width="120" align="center">
            <template #default="{ row }">
              {{ formatDate(row.repaymentDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="repaymentAmount" label="应还金额" width="120" align="right">
            <template #default="{ row }">
              ¥{{ formatAmount(row.repaymentAmount) }}
            </template>
          </el-table-column>
          <el-table-column prop="principal" label="应还本金" width="120" align="right">
            <template #default="{ row }">
              ¥{{ formatAmount(row.principal) }}
            </template>
          </el-table-column>
          <el-table-column prop="interest" label="应还利息" width="120" align="right">
            <template #default="{ row }">
              ¥{{ formatAmount(row.interest) }}
            </template>
          </el-table-column>
          <el-table-column prop="remainingPrincipal" label="剩余本金" width="120" align="right">
            <template #default="{ row }">
              ¥{{ formatAmount(row.remainingPrincipal) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getRepaymentStatusType(row.status)">
                {{ getRepaymentStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="实际还款日期" width="120" align="center">
            <template #default="{ row }">
              {{ row.actualRepaymentDate ? formatDate(row.actualRepaymentDate) : '-' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template #default="{ row }">
              <el-button 
                v-if="row.status === 1" 
                type="primary" 
                size="small" 
                @click="repayNow(row)"
              >
                立即还款
              </el-button>
              <span v-else class="operation-placeholder">-</span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="plan-summary" v-if="planSummary">
        <h4>还款汇总</h4>
        <div class="summary-grid">
          <div class="summary-item">
            <span class="summary-label">应还总额：</span>
            <span class="summary-value">¥{{ formatAmount(planSummary.totalAmount) }}</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">应还本金：</span>
            <span class="summary-value">¥{{ formatAmount(planSummary.totalPrincipal) }}</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">应还利息：</span>
            <span class="summary-value">¥{{ formatAmount(planSummary.totalInterest) }}</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">已还总额：</span>
            <span class="summary-value positive">¥{{ formatAmount(planSummary.paidAmount) }}</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">剩余应还：</span>
            <span class="summary-value highlight">¥{{ formatAmount(planSummary.remainingAmount) }}</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">逾期期数：</span>
            <span class="summary-value" :class="planSummary.overdueCount > 0 ? 'negative' : ''">
              {{ planSummary.overdueCount }}期
            </span>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="$emit('update:visible', false)">关闭</el-button>
        <el-button type="primary" @click="exportPlan" :disabled="!repaymentPlans.length">
          导出计划
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { getRepaymentPlan, getLoanDetail } from '@/api/loan';

const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  loanId: {
    type: Number,
    default: null
  }
});

const emit = defineEmits(['update:visible', 'repay']);

// 响应式数据
const loading = ref(false);
const repaymentPlans = ref([]);
const loanInfo = ref(null);

// 计算属性
const planSummary = computed(() => {
  if (!repaymentPlans.value.length) return null;
  
  const totalAmount = repaymentPlans.value.reduce((sum, plan) => sum + (plan.repaymentAmount || 0), 0);
  const totalPrincipal = repaymentPlans.value.reduce((sum, plan) => sum + (plan.principal || 0), 0);
  const totalInterest = repaymentPlans.value.reduce((sum, plan) => sum + (plan.interest || 0), 0);
  const paidAmount = repaymentPlans.value
    .filter(plan => plan.status === 2)
    .reduce((sum, plan) => sum + (plan.repaymentAmount || 0), 0);
  const remainingAmount = totalAmount - paidAmount;
  const overdueCount = repaymentPlans.value.filter(plan => plan.status === 3).length;
  
  return {
    totalAmount,
    totalPrincipal,
    totalInterest,
    paidAmount,
    remainingAmount,
    overdueCount
  };
});

// 工具函数
const formatAmount = (amount) => {
  if (amount === undefined || amount === null) return '0.00';
  return parseFloat(amount).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

const formatDate = (dateTime) => {
  if (!dateTime) return '-';
  const date = new Date(dateTime);
  return date.toLocaleDateString('zh-CN');
};

const getRepaymentMethodText = (method) => {
  const methodMap = {
    1: '等额本息',
    2: '等额本金',
    3: '一次性还本付息'
  };
  return methodMap[method] || '未知';
};

const getRepaymentStatusText = (status) => {
  const statusMap = {
    1: '待还款',
    2: '已还款',
    3: '逾期'
  };
  return statusMap[status] || '未知';
};

const getRepaymentStatusType = (status) => {
  const typeMap = {
    1: 'warning',
    2: 'success',
    3: 'danger'
  };
  return typeMap[status] || 'info';
};

// 数据加载方法
const loadRepaymentPlans = async () => {
  if (!props.loanId) return;
  
  loading.value = true;
  try {
    // 并行加载贷款信息和还款计划
    const [loanResponse, planResponse] = await Promise.all([
      getLoanDetail(props.loanId),
      getRepaymentPlan(props.loanId)
    ]);
    
    loanInfo.value = loanResponse.data;
    repaymentPlans.value = planResponse.data || [];
  } catch (error) {
    console.error('加载还款计划失败：', error);
    ElMessage.error('加载还款计划失败');
  } finally {
    loading.value = false;
  }
};

// 操作方法
const repayNow = (plan) => {
  emit('repay', {
    loanId: props.loanId,
    planId: plan.id,
    amount: plan.repaymentAmount
  });
};

const exportPlan = () => {
  // 导出功能的简单实现
  if (!repaymentPlans.value.length) {
    ElMessage.warning('暂无还款计划可导出');
    return;
  }
  
  // 这里可以实现导出到Excel或CSV的功能
  ElMessage.info('导出功能开发中...');
};
</script>

<style scoped>
.repayment-plan-content {
  padding: 8px;
}

.plan-header {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.plan-header h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  color: #303133;
}

.loan-info {
  display: flex;
  gap: 24px;
  font-size: 14px;
  color: #606266;
}

.plans-table {
  margin-bottom: 20px;
}

.operation-placeholder {
  color: #c0c4cc;
  font-size: 14px;
}

.plan-summary {
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.plan-summary h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: #303133;
}

.summary-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 12px;
  background-color: white;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.summary-label {
  color: #909399;
  font-size: 14px;
}

.summary-value {
  color: #303133;
  font-weight: 600;
  font-size: 14px;
}

.summary-value.positive {
  color: #67c23a;
}

.summary-value.negative {
  color: #f56c6c;
}

.summary-value.highlight {
  color: #e6a23c;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .loan-info {
    flex-direction: column;
    gap: 8px;
  }
  
  .summary-grid {
    grid-template-columns: 1fr;
  }
}
</style>
